<?php
/**
 *
 *
 */
namespace app\api\controller;

use think\Model;
use think\Controller;
use think\Db;
use app\api\model\Member as MemberModel;
use WordAnalysis\Analysis;
class Api extends Controller
{
    //前台评论提交
    public function commentAdd()
    {
        if (!session('username') || !session('userid')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapicommentAdd');
            $html = Db::name('comment');
            $id = input('id');
            $data = $this->request->post();
            //判断权限组 输出权限组
            if (stripos('0,' . qxz(session('userid'), 2), '2') == '') {
                $this->error('暂无权限');
            }
            $data['fid'] = $id;
            $data['time'] = time();
            $data['model'] = input('model');
            $data['uid'] = session('userid');
            $data['content'] = xss(input('content'));
            if (empty(input('content'))) {
                $this->error('内容不能为空');
            }
            if (!empty(input('tid'))) {
                $data['tid'] = input('tid');
            }
            if (mb_strlen(input('content'), 'UTF-8')>500) {
                $this->error('评论内容字数不能大于500');
            }
            //评论奖励积分
            point(cms('commentpoint'), session('userid'), '评论');
            //加经验
            Db::name('member')->where('userid', session('userid'))->setInc('jingyan', cms('commentpoint'));
            //查询当前主题作者的uid
            $duid = fun_sc_p(m(input('model')), array('id' => $id), 'uid');
            $duidt = fun_sc_p('comment', array('id' => input('tid')), 'uid');
            //评论邮件通知该主题作者开启
            if (cms('usernamemail') == 1) {
                //输出当前主题的url
                $url = '' . http() . '' . $_SERVER['SERVER_NAME'] . '/s_' . m(input('model')) . '_' . $id . 'html';
                //输出当前主题的标题
                $title = fun_sc_p(m(input('model')), array('id' => $id), 'title');
                //查询当前主题作者邮箱
                $toemail = fun_sc_p('member', array('userid' => $duid), 'usermail');
                $subject = '您的主题' . $title . '有人回复了';
                $content = '您的主题:' . $title . '有人回复了<br><br><a href="' . $url . '" target="_blank">' . $url . '</a>';
                send_mail($toemail, $subject, $content);
            }
            //评论消息通知作者
            xiaoxiadd($id, session('userid'), $duid, input('model'));
            if (!empty(input('tid'))) {
                xiaoxiadd($id, session('userid'), $duidt, input('model'));
            }
            if (!$html->data($data)->insert()) {
                $this->error('评论失败');
            } else {
                $this->success('评论成功');
            }
        }
    }
    //前台评论单页提交
    public function commentdan()
    {
        if (!session('username') || !session('userid')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapicommentdan');
            $html = Db::name('comment');
            $id = input('id');
            $data = $this->request->post();
            $data['fid'] = $id;
            $data['time'] = time();
            $data['model'] = 0;
            $data['uid'] = session('userid');
            $data['content'] = xss(input('content'));
            if (empty(input('content'))) {
                $this->error('内容不能为空');
            }
             
            if (mb_strlen(input('content'), 'UTF-8')>500) {
                $this->error('评论内容字数不能大于500');
            }
            //查询今日当前单页留言数量
            $J = Date_k(0);
            $Z = Date_k(1);
            $cxdy = $html->where("time > $J and time < $Z")->where(array('fid' => $id, 'model' => 0, 'uid' => session('userid')))->count();
            if ($cxdy >= fun_sc_p('danye', array('id' => $id), 'pl')) {
                $this->error('今天留言过多明天再来');
            }
            //评论奖励积分
            point(fun_sc_p('danye', array('id' => $id), 'jifen'), session('userid'), '评论');
            //加经验
            Db::name('member')->where('userid', session('userid'))->setInc('jingyan', fun_sc_p('danye', array('id' => $id), 'jifen'));
            //评论邮件通知该？
            if (fun_sc_p('danye', array('id' => $id), 'mail') == 1) {
                //输出当前单页的url
                $url = '' . http() . '' . $_SERVER['SERVER_NAME'] . '/d_' . fun_sc_p('danye', array('id' => $id), 'show') . '.html';
                //输出当前单页的标题
                $title = fun_sc_p('danye', array('id' => $id), 'title');
                //管理员邮箱
                $toemail = cms('mailUsername');
                $subject = '有人在' . $title . '回复了';
                $content = '有人在:' . $title . '回复了<br><br><a href="' . $url . '" target="_blank">' . $url . '</a>';
                send_mail($toemail, $subject, $content);
            }
            if (!$html->data($data)->insert()) {
                $this->error('留言失败');
            } else {
                $this->success('留言成功');
            }
        }
    }
    //用户登录
    public function homeLogin()
    {
        if (session('userid') != '') {
            // echo "<script>history.go(-1);</script>";
            $this->error('您已登录');
        }
        $member = new MemberModel();
        if (request()->isPost()) {
        	h('phpapihomeLogin');
            $data = input('post.');
            $open['open'] = 1;
            $map['usermail'] = $data['username'];
            $key = 'www.115cms.com';
            //不能随便更改会导致用户无法登录
            $user = Db::name('member')->where($open)->where($map)->find();
            if ($user) {
                if (jiami($user['password'], 'DECODE', $key, 0) == $data['password']) {
                    session('username', $user['username']);
                    session('usermail', $user['usermail']);
                    session('userid', $user['userid']);
                    $member->where($map)->setField(array('last_login_ip' => $_SERVER['REMOTE_ADDR'], 'last_login_time' => time()));
                    //登录送积分
                    point(cms('loginpoint'), session('userid'), 'login');
                    //加经验
                    $member->where($map)->setInc('jingyan', cms('loginpoint'));
                    h('phpapihomeLogina');
                    return json(array('code' => 200, 'msg' => '登录成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '密码错误'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '账号错误'));
            }
        }
    }
    //注册
    public function homereg()
    {
        if (session('userid') || session('username')) {
            echo "<script>history.go(-1);</script>";
        }
        $member = new MemberModel();
        if (request()->isPost()) {
        	h('phpapihomereg');
            $data = input('post.');
            $password = input('password');
            $key = 'www.115cms.com';
            //不能随便更改会导致用户无法登录
            $mail = $member->where('usermail', $data['usermail'])->find();
            // session_start();
            if (cms('reghomes') == 0) {
                $open = 1;
            } else {
                $open = 0;
            }
            //关闭图形码验证
            if (cms('regtxm') == 1) {
                $imgId_req = $_REQUEST['yzm'];
                if ($_SESSION['checkkey'] != $imgId_req) {
                    $this->error('图形码错误');
                }
            }
            //关闭邮箱验证注册
            if (cms('regmail') == 1) {
                if (session('code') != input('code')) {
                    $this->error('邮箱验证码错误');
                }
                if (session('codemails') != $data['usermail']) {
                    $this->error('请不要更换邮箱');
                }
                
            }
            if (!$mail) {
                $user = $member->where('usermail', $data['usermail'])->find();
                if (!is_email($data['usermail'])) {
                    $this->error('邮箱格式错误');
                }
                $data['regtime'] = time();
                if (cms('regmail') == 1) {
                    $data['mailopen'] = 1;
                } else {
                    $data['mailopen'] = 0;
                }
                $data['dengji'] = 0;
                $data['open'] = $open;
                $data['point'] = cms('loginpoint');
                $data['username'] = suiji(10);
                $data['userhead'] = '/public/img/touxiang.jpg';
                $data['userip'] = $_SERVER['REMOTE_ADDR'];
                $data['password'] = jiami($password, 'ENCODE', $key, 0);
                if ($member->add($data)) {
                    //注册送积分
                    point(cms('regpoint'), session('userid'), '注册');
                    //加经验
                    $member->where('usermail', $data['usermail'])->setInc('jingyan', cms('regpoint'));
                    return json(array('code' => 200, 'msg' => '注册成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '注册失败'));
                }
            } else {
                return json(array('code' => 0, 'msg' => '该邮箱已存在'));
            }
        }
    }
    //找回密码
    public function homeretrieve()
    {
        $member = new MemberModel();
        if (request()->isPost()) {
        	h('phpapihomereg');
            $data = input('post.');
            $password = input('password');
            $key = 'www.115cms.com';
            //不能随便更改会导致用户无法登录
            $mail = $member->where('usermail', $data['usermail'])->find();
            if (!$mail) {
                return json(array('code' => 0, 'msg' => '该邮箱不存在'));
            } else {
                if (session('coderetrieve') != input('code')) {
                    $this->error('邮箱验证码错误');
                }
                if (session('codemail') != $data['usermail']) {
                    $this->error('请不要更换邮箱');
                }
                $user = $member->where('usermail', $data['usermail'])->find();
                if (!is_email($data['usermail'])) {
                    $this->error('邮箱格式错误');
                }
                    $datam['password'] = jiami($password, 'ENCODE', $key, 0);
                    if ($member->save($datam, ['usermail' => $data['usermail']])) {
                        return json(array('code' => 200, 'msg' => '修改成功'));
                    } else {
                        return json(array('code' => 0, 'msg' => '修改失败'));
                    }
            }
        }
    }
    /*退出*/
    public function tuichu()
    {
    	h('phptuichu');
        session("userid", NULL);
        session("username", NULL);
        session("usermail", NULL);
        session("phone", NULL);
        return json(array('code' => 200, 'msg' => '退出成功'));
        return NULL;
    }
    /*基本设置资料修改*/
    public function homeset()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
            $member = new MemberModel();
            $uid = session('userid');
            if (request()->isPost()) {
            	h('phpapihomeset');
                $data = $this->request->post();
                $data['userid'] = $uid;
                $_data['username'] = xss($data['username']); 
                if (mb_strlen($_data['username'], 'UTF-8')>12) {
                $this->error('用户名不能大于12个字符');
                }
                if (is_numeric($_data['username']) || is_numeric(substr($_data['username'], 0, 1)) || mb_strwidth($_data['username']) < 4) {
                    return json(array('code' => 0, 'msg' => '不能是纯数字或数字开头，一个汉字算2个字符'));
                }
                $_data['userhome'] = xss($data['userhome']);
                $_data['description'] = xss($data['description']);
                $_data['sex'] = $data['sex'];
                if( @fopen( $data['userhead'], 'r' ) ) 
                { 
                	$_data['userhead'] = xss($data['userhead']);
                } else {
                	if($data['userhead']== '/public/img/touxiang.jpg') { 
                		$_data['userhead'] = xss($data['userhead']);
                	} else {
                		$this->error('请上传正确的头像');
                	}
                }
                $_data['userqq'] = $data['userqq'];
                if(!CheckUrl($data['url'])){
                	$this->error('网址格式不正确');
                }else{
                	$urls =parse_url($data['url']);
                	$_data['url'] = $urls['scheme'].'://'.$urls['host'];
                }
                if (cms('homemail') == 1) {
                	if (!is_email($data['usermail'])) {
                		$this->error('邮箱格式错误');
                	}
                    $_data['usermail'] = $data['usermail'];
                }
                if ($member->save($_data, ['userid' => $uid])) {
                    return json(array('code' => 200, 'msg' => '修改成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '修改失败'));
                }
            }
            $uid = session('userid');
            $this->assign('uid', $uid);
        }
    }
    /*修改密码*/
    public function homepass()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapihomepass');
            $member = new MemberModel();
            $uid = session('userid');
            $key = 'www.115cms.com';
            if (request()->isPost()) {
                $data = $this->request->post();
                $password = input('password');
                if (input('password') == input('passwords')) {
                    $datam['password'] = jiami($password, 'ENCODE', $key, 0);
                    if ($member->save($datam, ['userid' => $uid])) {
                        return json(array('code' => 200, 'msg' => '修改成功'));
                    } else {
                        return json(array('code' => 0, 'msg' => '修改失败'));
                    }
                } else {
                    return json(array('code' => 0, 'msg' => '两次输入的密码不一致'));
                }
            }
        }
    }
    /*前台提交发布*/
    public function homeadd()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapihomeadd');
            //判断权限组 输出权限组
            if (stripos('0,' . qxz(session('userid'), 2), '3') == '') {
                $this->error('暂无权限');
            }
            if (fun_sc_p('cate', array('id' => input('tid')), 'tougao') == 0) {
                $this->error('不要瞎搞,当前栏目禁止投稿');
            }
            if (fun_sc_p('cate', array('id' => input('tid')), 'model') != input('id')) {
                $this->error('不要瞎搞,不能跨模型提交');
            }
            $data = $this->request->post();
            $data['time'] = time();
            $data['times'] = time();
            //判断权限组 输出权限组
            if (stripos('0,' . qxz(session('userid'), 2), '4') == '') {
            	$data['open'] = fun_sc_p('cate', array('id' => input('tid')), 'sh');
            } else {
                $data['open'] = 1;
            }
            $data['uid'] = session('userid');
            $data['model'] = fun_sc_p('cate', array('id' => input('tid')), 'model');
            $data['description'] = xss(htmltext(input('content')));
            $data['content'] = xss(input('content'));
            $data['title'] = xss(input('title'));
            $data['pic'] = xss(input('pic'));
            $content = preg_replace("/[a-z,A-Z]|[0-9]|[[:punct:]]/i", "", htmlspecialchars_decode(input('content')));
            if (empty(input('keywords'))) {
                $data['keywords'] = Analysis::getKeywords($content);
            } else {
            	$data['keywords'] = xss(input('keywords'));
            }
            $data['file'] = xss(input('file'));
            $data['zan'] = 0;
            /*自定义字段过滤*/
            $wanneng = Db::name('modelZiduan')->where('tid', $data['model'])->select();
            foreach ($wanneng as $html) {
                $data[$html['name']] = xss(input($html['name']));
            }
            $name = fun_sc_p('model', array('id' => $data['model']), 'name');
            $html = Db::name($name);
            if (!$html->data($data)->strict(false)->insert()) {
                $this->error('添加失败');
            } else {
                //邮件通知站长
                if (cms('mailadmin') == 1) {
                    $url = '' . http() . '' . $_SERVER['SERVER_NAME'] . '';
                    $toemail = cms('mailUsername');
                    $subject = '有人在' . cms('title') . '投稿了作品';
                    $content = '有人在' . cms('title') . '投稿了作品快去看看吧!<br><br><a href="' . $url . '" target="_blank">' . $url . '</a>';
                    send_mail($toemail, $subject, $content);
                }
                h('phpapihomeadda');
                model_whole(fun_sc_p($name, array('time' => $data['time']), 'id'), session('userid'), $data['model']);
                $this->success('发布成功');
            }
        }
    }
    /*前台修改发布*/
    public function homeedit()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapihomeedit');
            if (fun_sc_p('cate', array('id' => input('tid')), 'tougao') == 0) {
                $this->error('不要瞎搞,当前栏目禁止投稿');
            }
            if (fun_sc_p('cate', array('id' => input('tid')), 'model') != fun_sc_p(m(fun_sc_p('cate', array('id' => input('tid')), 'model')), array('id' => input('id')), 'model')) {
                $this->error('不要瞎搞,不能跨模型提交');
            }
            $data = $this->request->post();
            $data['times'] = time();
            $data['open'] = fun_sc_p('cate', array('id' => input('tid')), 'sh');
            $data['uid'] = session('userid');
            $data['id'] = input('id');
            $data['model'] = fun_sc_p('cate', array('id' => input('tid')), 'model');
            $data['description'] = xss(htmltext(input('content')));
            $data['content'] = xss(input('content'));
            $data['title'] = xss(input('title'));
            $data['pic'] = xss(input('pic'));
            $content = preg_replace("/[a-z,A-Z]|[0-9]|[[:punct:]]/i", "", htmlspecialchars_decode(input('content')));
            if (empty(input('keywords'))) {
                $data['keywords'] = Analysis::getKeywords($content);
            } else {
            	$data['keywords'] = xss(input('keywords'));
            }
            $data['file'] = xss(input('file'));
            $data['zan'] = 0;
            /*自定义字段过滤*/
            $wanneng = Db::name('modelZiduan')->where('tid', $data['model'])->select();
            foreach ($wanneng as $html) {
                $data[$html['name']] = xss(input($html['name']));
            }
            $name = fun_sc_p('model', array('id' => $data['model']), 'name');
            $html = Db::name($name);
            if (!$html->data($data)->strict(false)->update()) {
                $this->error('更新失败');
            } else {
            	h('phpapihomeedita');
                $this->success('更新成功');
            }
        }
    }
    /*消息*/
    public function xiaoxi()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpxiaoxi');
            if (input('id') == 1) {
                if (Db::name('xiaoxi')->where('id', input('ids'))->where('userid', session('userid'))->setField('open', '0')) {
                    return json(array('code' => 200, 'msg' => '标记已读成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '标记已读失败'));
                }
            } elseif (input('id') == 0) {
                if (Db::name('xiaoxi')->where('id', input('ids'))->where('userid', session('userid'))->delete()) {
                    return json(array('code' => 200, 'msg' => '彻底删除成功'));
                } else {
                    return json(array('code' => 0, 'msg' => '彻底删除失败'));
                }
            }
        }
    }
    /*发送消息*/
    public function xiaoxiadd()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapixiaoxiadd');
            $data = $this->request->post();
            //判断权限组 输出权限组
            if (stripos('0,' . qxz(session('userid'), 2), '1') == '') {
                $this->error('暂无权限');
            }
            //查询用户是否存在
            $xc = fun_st('member', array('open' => 1, 'userid' => input('userid')));
            if ($xc == 0) {
                $this->error('用户不存在');
            }
            //查询是否是本人
            if (input('userid') == session('userid')) {
                $this->error('太自恋了');
            }
            $data['tid'] = 0;
            $data['uid'] = session('userid');
            $data['userid'] = input('userid');
            $data['content'] = xss(input('content'));
            $data['open'] = 1;
            $data['model'] = 0;
            $data['time'] = time();
            if (!Db::name('xiaoxi')->data($data)->insert()) {
                $this->error('发送失败');
            } else {
                $this->success('发送成功');
            }
        }
    }
    /*点赞*/
    public function zan()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpzan');
            //查询是否点赞过
            $t = Db::name('zan')->where('uid', session('userid'))->where('tid', input('id'))->where('model', input('m'))->count();
            if ($t > 0) {
                $this->error('不能多次点赞');
                return false;
            }
            $uid = fun_sc_p(m(input('m')), array('id' => input('id')), 'uid');
            $data['tid'] = input('id');
            $data['uid'] = session('userid');
            $data['suid'] = $uid;
            $data['fl'] = 1;
            //1文章是点赞
            $data['open'] = 1;
            $data['model'] = input('m');
            $data['time'] = time();
            if (!Db::name('zan')->data($data)->insert()) {
                $this->error('点赞失败');
            } else {
                //给作品赞+1
                Db::name(m(input('m')))->where('id', input('id'))->setInc('zan', 1);
                //加经验
                Db::name('member')->where('userid', session('userid'))->setInc('jingyan', cms('zanjingyan'));
                $this->success('点赞成功');
            }
        }
    }
    /*收藏*/
    public function shoucang()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapishoucang');
            //查询是否点收藏过
            $t = Db::name('shoucang')->where('uid', session('userid'))->where('tid', input('id'))->where('model', input('m'))->count();
            if ($t > 0) {
                if (!Db::name('shoucang')->where('tid', input('id'))->where('uid', session('userid'))->where('model', input('m'))->where('fl', 1)->where('tid', input('id'))->delete()) {
                    $this->error('取消收藏失败');
                } else {
                    return json(array('code' => 2, 'msg' => '取消收藏成功'));
                }
            }
            $data['tid'] = input('id');
            $data['uid'] = session('userid');
            $data['fl'] = 1;
            //1模型收藏
            $data['open'] = 1;
            $data['model'] = input('m');
            $data['time'] = time();
            if (!Db::name('shoucang')->data($data)->insert()) {
                $this->error('收藏失败');
            } else {
                //加经验
                Db::name('member')->where('userid', session('userid'))->setInc('jingyan', cms('scjingyan'));
                $this->success('收藏成功');
            }
        }
    }
    /*付费阅读*/
    public function fufei()
    {
        if (!session('userid') || !session('username')) {
            $this->error('亲！请登录');
        } else {
        	h('phpapifufei');
            //查询是否点付费过
            $t = Db::name('fufei')->where('uid', session('userid'))->where('tid', input('id'))->where('model', input('m'))->count();
            if ($t > 0) {
                $this->error('不需要重复付费');
                return false;
            }
            //权限免付费
            if (stripos('0,' . qxz(session('userid'), 2), '5') != '') {
                //添加付费记录
                $data['tid'] = input('id');
                $data['uid'] = session('userid');
                $data['jifen'] = $jifen;
                $data['open'] = 1;
                $data['model'] = input('m');
                $data['time'] = time();
                if (!Db::name('fufei')->data($data)->insert()) {
                    $this->error('免付费失败');
                } else {
                    Db::name('member')->where('userid', $uid)->setInc('jingyan', $jifen);
                    $this->success('免付费成功');
                }
            }
            //查询当前文章的付费积分
            $jifen = fun_sc_p(m(input('m')), array('id' => input('id')), 'jifen');
            $uid = fun_sc_p(m(input('m')), array('id' => input('id')), 'uid');
            //查询用户积分余额
            $point = Db::name('member')->where('userid', session('userid'))->value('point');
            if ($point < $jifen && $jifen > 0) {
                $this->error('余额不足请');
            } else {
                //添加付费记录
                $data['tid'] = input('id');
                $data['uid'] = session('userid');
                $data['jifen'] = $jifen;
                $data['open'] = 1;
                $data['model'] = input('m');
                $data['time'] = time();
                if (!Db::name('fufei')->data($data)->insert()) {
                    $this->error('付费失败');
                } else {
                    //开始扣分
                    point(-$jifen, session('userid'), '付费阅读');
                    //开始加分
                    point($jifen, $uid, '付费阅读');
                    //给作者添加经验
                    Db::name('member')->where('userid', $uid)->setInc('jingyan', $jifen);
                    $this->success('付费成功');
                }
            }
        }
    }
    public function czsj()
    {
    	$data['model'] = $_GET['model'];
        $data['dianji'] = $_GET['dianji'];
    	$sc = Db::name('model_ziduan_l')->where($data)->value('yingchang');
        $whereArr['open'] = 1;
        $wanneng = Db::name('model_ziduan')->field('name')->where(array('tid' => $_GET['model']))->where('name','not in',$sc)->select();
        $html = json_encode($wanneng);
        $a = json_encode($html);
        $b = json_decode($a, true);
        print_r($b);
        /*
        foreach ($wanneng as $html) {
        	return json(array('code' => 2, 'msg' => '<script>$(document).ready(function(){$("#'.$html['name'].'").hide();});</script>'));
        }
        */
     }
}